const { sequelize } = require('../config/database')
const User = require('./User')
const Course = require('./Course')
const Chat = require('./Chat')
const AiConfig = require('./AiConfig')
const ChatSession = require('./ChatSession')
const ChatMessage = require('./ChatMessage')
const SystemConfig = require('./SystemConfig')
const StudentProgress = require('./StudentProgress')
const ChapterConfig = require('./ChapterConfig')
const ChapterHighlights = require('./ChapterHighlights')
const Chapter = require('./Chapter')
const Lecture = require('./Lecture')

// 定义模型关联关系

// User 和 Chat 的关联
User.hasMany(Chat, {
  foreignKey: 'userId',
  as: 'chats'
})
Chat.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
})

// User 和 Course 的关联（如果需要课程创建者）
User.hasMany(Course, {
  foreignKey: 'creatorId',
  as: 'createdCourses'
})
Course.belongsTo(User, {
  foreignKey: 'creatorId',
  as: 'creator'
})

// User 和 AiConfig 的关联
User.hasMany(AiConfig, {
  foreignKey: 'userId',
  as: 'aiConfigs'
})
AiConfig.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
})

// User 和 ChatSession 的关联
User.hasMany(ChatSession, {
  foreignKey: 'userId',
  as: 'chatSessions'
})
ChatSession.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
})

// ChatSession 和 ChatMessage 的关联
ChatSession.hasMany(ChatMessage, {
  foreignKey: 'sessionId',
  as: 'messages'
})
ChatMessage.belongsTo(ChatSession, {
  foreignKey: 'sessionId',
  as: 'session'
})

// User 和 StudentProgress 的关联
User.hasMany(StudentProgress, {
  foreignKey: 'userId',
  as: 'studentProgresses'
});
StudentProgress.belongsTo(User, {
  foreignKey: 'userId',
  as: 'user'
});

// Course 和 StudentProgress 的关联
Course.hasMany(StudentProgress, {
  foreignKey: 'courseId',
  as: 'studentProgresses'
});
StudentProgress.belongsTo(Course, {
  foreignKey: 'courseId',
  as: 'course'
});

// User 和 ChapterConfig 的关联
User.hasMany(ChapterConfig, {
  foreignKey: 'createdBy',
  as: 'createdChapterConfigs'
});
ChapterConfig.belongsTo(User, {
  foreignKey: 'createdBy',
  as: 'creator'
});

User.hasMany(ChapterConfig, {
  foreignKey: 'updatedBy',
  as: 'updatedChapterConfigs'
});
ChapterConfig.belongsTo(User, {
  foreignKey: 'updatedBy',
  as: 'updater'
});

// User 和 ChapterHighlights 的关联
User.hasMany(ChapterHighlights, {
  foreignKey: 'createdBy',
  as: 'createdChapterHighlights'
});
ChapterHighlights.belongsTo(User, {
  foreignKey: 'createdBy',
  as: 'creator'
});

User.hasMany(ChapterHighlights, {
  foreignKey: 'updatedBy',
  as: 'updatedChapterHighlights'
});
ChapterHighlights.belongsTo(User, {
  foreignKey: 'updatedBy',
  as: 'updater'
});

// Chapter 和 Lecture 的关联
Chapter.hasMany(Lecture, {
  foreignKey: 'chapter_id',
  as: 'lectures'
});
Lecture.belongsTo(Chapter, {
  foreignKey: 'chapter_id',
  as: 'chapter'
});

// 导出所有模型和sequelize实例
module.exports = {
  sequelize,
  User,
  Course,
  Chat,
  AiConfig,
  ChatSession,
  ChatMessage,
  SystemConfig,
  StudentProgress,
  ChapterConfig,
  ChapterHighlights,
  Chapter,
  Lecture
}